package com.i2bt.app.files.model;

import com.i2bt.common.UserConfig;

import com.i2bt.R;
import com.i2bt.app.BaseActivity;
import com.i2bt.app.main.MainActivity;
import com.i2bt.bean.FilesTransmissionBean;
import com.i2bt.util.FileSizeConvertUtil;

import android.os.Environment;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class FilesDownloadClient extends Thread{

	private BaseActivity activity; // 活动类

	private Socket downloadSocket; // 下载客户端

	private FilesTransmissionBean[] transmissionBeans; // 文件路径列表

	private String ip; // ip地址

	private int port; // 端口号

	private BufferedOutputStream filesLocalOutput; // 本地文件写入

	private DataInputStream filesRemoteInput; // 远程文件读取

	private onDownloadListener downloadListener; // 下载监听器

	public FilesDownloadClient(BaseActivity activity, String ip, int port, 
			FilesTransmissionBean[] transmissionBeans, onDownloadListener downloadListener) {
		// 初始化
		downloadSocket = new Socket();
		this.activity = activity;
		this.ip = ip;
		this.port = port;
		this.transmissionBeans = transmissionBeans;
		this.downloadListener = downloadListener;
		init();
	}

	/**
	 * 初始化
	 */
	private void init() {
		// 排队
		for ( FilesTransmissionBean transmissionBean : transmissionBeans) {
			//添加下载的传输列表项
			String fileSize = FileSizeConvertUtil.autoConvert(transmissionBean.getFileLength());
			char space = fileSize.charAt(fileSize.length() - 1);
			String info = "0" + space + "/" + fileSize;
			MainActivity.transmission.addDownload(R.drawable.files_icon_image, 
					transmissionBean.getFileName(), info, 
					UserConfig.currentFilesPath + transmissionBean.getFileName());
			
			transmissionBean.setMessage("排队下载..");
			downloadListener.onDownloadUpdate();
		}
	}

	@Override
	public void run() {
		super.run();

		//连接服务器
		try {
			downloadSocket = new Socket(ip, port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			activity.toastHandler("找不到homebox");
			return;
		} catch (IOException e) {
			e.printStackTrace();
			activity.toastHandler("连接失败");
			return;
		}


		// 获取存储路径
		String savePath = activity.readXML("SETTING", "DOWNLOADPATH");
		if (savePath == null) {
			savePath = Environment.getExternalStorageDirectory().getAbsolutePath();
		}

		// 缓存长度
		int bufferedLength = 1024;
		// 缓存字节数组
		byte[] buffer = new byte[bufferedLength];
		// 读取的长度
		int readlength = 0;

		// 向服务器获取对应的文件
		for (int i = 0; i < transmissionBeans.length; i++) {

			try {
				// 完成的进度数
				int sum = 0;

				activity.toastHandler("开始下载第" + (i + 1) + "个文件");
				System.out.println("准备开始下载第" + (i + 1) + "个文件");
				
				File file = new File(savePath + "/" + transmissionBeans[i].getFileName());
				filesLocalOutput = new BufferedOutputStream(new FileOutputStream(file));
				System.out.println("装载输入");
				filesRemoteInput = new DataInputStream(
						new BufferedInputStream(downloadSocket.getInputStream()));
				
				System.out.println("装载输出");
				
				transmissionBeans[i].setMessage("下载中..");
				downloadListener.onDownloadUpdate();
				
				activity.toastHandler("下载中...");

				// 读取远程发过来的数据, 并写入本地
				while (true) {
					
					readlength = filesRemoteInput.read(buffer, 0, bufferedLength);
					System.out.println("下载中1..");
					// 表示读完, 跳出循环
					if (readlength == -1) {
						break;
					}
					
					System.out.println("下载中2..");
					
					filesLocalOutput.write(buffer, 0, bufferedLength);

					// 增加下载进度
					sum += readlength;

					// 更新下载进度
					transmissionBeans[i].setProgressSum(sum);
					downloadListener.onDownloadUpdate();
					
					long fileLength = transmissionBeans[i].getFileLength();
//					MainActivity.transmission.setProgress(0, i, (int) (sum / fileLength * 100));
					
					System.out.println("下载了" + sum);
				}

				// 把缓存下载到本地
				filesLocalOutput.flush();

				transmissionBeans[i].setMessage("下载完成..");
				
				downloadListener.onDownloadUpdate();
				System.out.println("下载完第" + (i + 1) + "个");

				activity.toastHandler("下载完第" + (i + 1) + "个文件");

			} catch (FileNotFoundException e) {
				
				e.printStackTrace();
				transmissionBeans[i].setMessage("下载失败");
				downloadListener.onDownloadUpdate();
				
			} catch (IOException e) {
				
				e.printStackTrace();
				transmissionBeans[i].setMessage("下载失败");
				downloadListener.onDownloadUpdate();
				
			} finally {
				
				try {
					filesLocalOutput.close();
					filesRemoteInput.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
			
		}

		activity.toastHandler("全部下载任务处理完!");

		try {
			downloadSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		downloadListener.onDownloadResult();

	}
	
	/**
	 * 获取传输路径的信息数组
	 * @return
	 */
	public FilesTransmissionBean[] getTransmissionBeans() {
		return transmissionBeans;
	}

	/**
	 * 设置监听器
	 * @param downloadListener
	 */
	public void setOnDownloadListener(onDownloadListener downloadListener) {
		this.downloadListener = downloadListener;
	}

	/**
	 * 
	 * Title : 下载监听器接口
	 *
	 * Description : 下载的时候会根据进度调用更新方法
	 *
	 * CreatedTime : 2014-8-28
	 *
	 * @author wuliao & kakaxi & yi
	 *
	 * @version 1.0
	 *
	 */
	public interface onDownloadListener {
		public void onDownloadUpdate();
		public void onDownloadResult();
	}

}
